#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import time
import random
import hashlib
import requests
from urllib.parse import quote, urlencode
import xml.etree.ElementTree as ET

try:
    import pycurl
    from cStringIO import StringIO
except ImportError:
    pycurl = None


class WxPayConf_pub(object):
    """配置账号信息"""
    #=======【基本信息设置】=====================================
    #微信公众号身份的唯一标识。审核通过后，在微信发送的邮件中查看
    APPID = "wx8930fb988e7ed70b"
    #JSAPI接口中获取openid，审核后在公众平台开启开发模式后可查看
    APPSECRET = "82adf3a3b4a9fbdf9a273c0d5a8e6f6c"
    TOKEN = "tianmuhongcheng"
    #受理商ID，身份标识
    # MCHID = "1585291301"
    #商户支付密钥Key。审核通过后，在微信发送的邮件中查看
    KEY = "c277798a0759d0b243f7c2d05796c549"
    #=======【异步通知url设置】===================================
    #异步通知url，商户根据实际开发过程设定
    NOTIFY_URL = "http://crpapitest.liuxue.com:52017/yupei/pay/"
    #=======【JSAPI路径设置】===================================
    #获取access_token过程中的跳转uri，通过跳转将code传入jsapi支付页面
    JS_API_CALL_URL = "http://crpapitest.liuxue.com:52017/yupei/pay/?showwxpaytitle=1"
    #=======【证书路径设置】=====================================
    #证书路径,注意应该填写绝对路径
    # SSLCERT_PATH = "/home/huchao/cert/apiclient_cert.pem"
    # SSLKEY_PATH = "/home/huchao/cert/apiclient_key.pem"
    #=======【curl超时设置】===================================
    CURL_TIMEOUT = 30
    #=======【HTTP客户端设置】===================================
    HTTP_CLIENT = "CURL"  # ("URLLIB", "CURL")


class Common_util_pub(object):
    """所有接口的基类"""
    VERIFY = False
    HEADERS = {}
    key = WxPayConf_pub.KEY

    def trimString(self, value):
        if value is not None and len(value) == 0:
            value = None
        return value

    def createNoncestr(self, length = 32):
        """产生随机字符串，不长于32位"""
        chars = "abcdefghijklmnopqrstuvwxyz0123456789"
        strs = []
        for x in range(length):
            strs.append(chars[random.randrange(0, len(chars))])
        return "".join(strs)

    def formatBizQueryParaMap(self, paraMap, urlencode):
        """格式化参数，签名过程需要使用"""
        slist = sorted(paraMap)
        buff = []
        for k in slist:
            v = quote(paraMap[k]) if urlencode else paraMap[k]
            buff.append("{0}={1}".format(k, v))

        return "&".join(buff)

    def setSandBoxnew(self, key=None):
            print('设置沙盒key')
            self.key = key
            try:
                self.url = self.url.replace('api.mch.weixin.qq.com', 'api.mch.weixin.qq.com/sandboxnew')
            except Exception:
                pass

    def getSign(self, obj, ismd5=True):
        """生成签名"""
        #签名步骤一：按字典序排序参数,formatBizQueryParaMap已做
        String = self.formatBizQueryParaMap(obj, False)
        #签名步骤二：在string后加入KEY
        String = "{0}&key={1}".format(String, self.key)
        #签名步骤三：MD5加密
        if ismd5:
            String = hashlib.md5(String.encode()).hexdigest()
        else:
            String = hashlib.sha256(String.encode()).hexdigest()
        #签名步骤四：所有字符转为大写
        result_ = String.upper()
        return result_

    def arrayToXml(self, arr):
        """array转xml"""
        xml = ["<xml>"]
        print(arr.items())
        for k, v in arr.items():
            print(k, v)
            if v.isdigit():
                xml.append("<{0}>{1}</{0}>".format(k, v))
            else:
                xml.append("<{0}><![CDATA[{1}]]></{0}>".format(k, v))
        xml.append("</xml>")
        return "".join(xml)

    def xmlToArray(self, xml):
        """将xml转为array"""
        array_data = {}
        root = ET.fromstring(xml)
        for child in root:
            value = child.text
            array_data[child.tag] = value
        return array_data
    
    def postXml(self, xml, url, second=30):
        """使用证书，以post方式提交xml到对应的接口url"""
        print('******************')
        print(url, xml)
        print('当前key===> {},\n线上key===>: {}'.format(self.key, WxPayConf_pub.KEY))
        print('******************')
        if self.VERIFY:
            resp = requests.post(url, data=xml.encode(), timeout=second, verify=self.VERIFY, headers=self.HEADERS)
        else:
            resp = requests.post(url, data=xml.encode(), timeout=second, headers=self.HEADERS)
        return resp.content
